<template>
  <div
    class="alarm-statistic"
    style="width: 100%; height: 100%"
    :style="{ backgroundColor: widgetOptions.setup.backgroundColor }"
  >
    <div class="alarm-header">
      <el-radio-group
        v-model="timeRangeType"
        :fill="widgetOptions.setup.timeActiveBgColor"
        :text-color="widgetOptions.setup.timeActiveFontColor"
        @change="refreshData"
      >
        <el-radio-button label="昨天" value="1" :style="getButtonStyle()" />
        <el-radio-button label="今天" value="2" :style="getButtonStyle()" />
        <el-radio-button label="近七天" value="3" :style="getButtonStyle()" />
        <el-radio-button label="近一月" value="4" :style="getButtonStyle()" />
      </el-radio-group>
      <el-radio-group
        v-model="groupField"
        :fill="widgetOptions.setup.timeActiveBgColor"
        :text-color="widgetOptions.setup.timeActiveFontColor"
        @change="refreshData"
      >
        <el-radio-button label="告警级别" value="alarm_level" :style="getButtonStyle()" />
        <el-radio-button label="被监测设备" value="monitor_device_name" :style="getButtonStyle()" />
      </el-radio-group>
    </div>
    <div class="alarm-body">
      <div v-if="!chartStatus" ref="chartRef" style="width: 100%; height: 100%"></div>
      <ChartEmpty v-if="chartStatus" :chartStatus="chartStatus" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useTools } from '../../../hooks/useTools'
import * as echarts from 'echarts'
import ChartEmpty from '../../../components/chartEmpty.vue'
import { AlarmRecordApi } from '@/api/vmiot/alarmrecord'
import { DICT_TYPE, getDictLabel } from '@/utils/dict'

// 接收父组件传入的值
const props = defineProps({
  widgetOptions: {
    type: Object as PropType<Record<string, any>>, // 或更具体的类型
    required: true
  },
  isPreview: {
    type: Boolean,
    default: false
  },
  tenantId: {
    type: Number,
    default: null
  }
})

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null
const chartData = ref<any>(null)
const chartStatus = ref('')
const refreshInterval = ref<any>()
const { toRgba } = useTools()
const timeRangeType = ref('1')
const groupField = ref('alarm_level')

const initChart = () => {
  if (chartRef.value) {
    // 初始化实例
    myChart = echarts.init(chartRef.value)
  }
}

// 更新配置
const updateOptions = () => {
  if (!chartData.value) return

  const xAxisData =
    groupField.value === 'monitor_device_name'
      ? chartData.value.map((item: any) => item.groupField)
      : chartData.value.map((item: any) => getDictLabel(DICT_TYPE.ALARM_LEVEL, item.groupField))

  const seriesData = chartData.value.map((item: any) => item.totalCount)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: props.widgetOptions.setup.xLineColor
        }
      },
      axisLabel: {
        color: props.widgetOptions.setup.xFontColor,
        fontSize: props.widgetOptions.setup.xFontSize
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: props.widgetOptions.setup.yLineColor
        }
      },
      axisLabel: {
        color: props.widgetOptions.setup.yFontColor,
        fontSize: props.widgetOptions.setup.yFontSize
      },
      splitLine: {
        show: props.widgetOptions.setup.ySplitLine,
        lineStyle: {
          color: 'rgba(255,255,255,0.2)'
        }
      }
    },
    series: [
      {
        data: seriesData,
        type: 'bar',
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: props.widgetOptions.setup.barColor2 },
            { offset: 1, color: props.widgetOptions.setup.barColor }
          ])
        }
      }
    ]
  }

  myChart?.setOption(option)
  myChart?.resize()
}

const getButtonStyle = () => {
  return {
    backgroundColor: props.widgetOptions.setup.timeBgColor,
    border: `1px solid ${props.widgetOptions.setup.timeBorderColor}`,
    color: props.widgetOptions.setup.timeFontColor
  }
}

// 启动定时器
const startInterval = () => {
  clearInterval(refreshInterval.value)
  if (props.widgetOptions.data.refreshTime > 0) {
    refreshInterval.value = setInterval(() => {
      getRealData()
    }, props.widgetOptions.data.refreshTime)
  }
}

const getRealData = async () => {
  try {
    const res = await AlarmRecordApi.getGroupCount({
      tenantId: props.tenantId,
      timeRangeType: timeRangeType.value,
      groupField: groupField.value
    })
    chartData.value = res
    updateOptions()
  } catch (e) {
    chartStatus.value = 'error'
  }
}

// 刷新数据
const refreshData = () => {
  if (props.isPreview) {
    getRealData()
    startInterval()
  } else {
    chartData.value = props.widgetOptions.data.statisticData
    updateOptions()
  }
}

onMounted(() => {
  initChart()
  refreshData()
})

// 如果父组件传入的 props.value 改变，需要更新折线图颜色等
watch(
  () => props.widgetOptions,
  () => {
    if (myChart) {
      updateOptions()
    }
  },
  { immediate: true, deep: true }
)

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
  clearInterval(refreshInterval.value)
})
</script>

<style scoped lang="scss">
.alarm-statistic {
  display: flex;
  flex-direction: column;
  padding: 10px;

  .alarm-header {
    display: flex;
    justify-content: space-between;
  }

  .alarm-body {
    flex: 1;
    min-height: 0;
  }

  :deep(.el-radio-button__inner) {
    background-color: transparent;
    border: none;
    color: inherit;
  }
}
</style>
